<template>
  <VTable
    v-if="isRefreshTable"
    ref="tableRef"
    v-bind="tableOptins"
    class="is--card"
    @keyup="handleKeyUp"
  >
    <template #form="{ form }">
      <select-category
        v-model="form.product_category"
        placeholder="产品分类"
        :defaultProps="defaultProps"
        filterable
        @change="changeCategory"
      ></select-category>
      <VGroup>
        <el-select
          class="selectClass w-[100px]"
          v-model="form.productName.type"
          style="max-width: 100px"
        >
          <el-option
            v-for="item of productOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <multi-input
          clearable
          v-model="form.productName.value"
          style="width: 180px"
          placeholder="批量搜索,一行一个"
        ></multi-input>
      </VGroup>
      <VGroup>
        <el-select
          class="selectClass !w-[100px]"
          v-model="form.dateRange.type"
          collapse-tags
          placeholder="创建时间"
        >
          <el-option
            v-for="item in dateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-date-picker
          v-model="form.dateRange.value"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="defaultTime()"
        />
      </VGroup>
      <el-select
        v-model="form.task_priority"
        collapse-tags
        placeholder="任务等级"
        clearable
        class="!w-[120px]"
        multiple
      >
        <el-option
          v-for="item of options['assignment.ImagesAssignment']?.[0].taskPriorityText"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-select
        v-model="form.priority"
        collapse-tags
        placeholder="优先级"
        clearable
        class="!w-[120px]"
        multiple
      >
        <el-option
          v-for="item of options['assignment.ImagesAssignment']?.[0].priorityText"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-select
        v-model="form.is_delay"
        class="!w-[160px]"
        placeholder="是否延期"
        clearable
      >
        <el-option
          v-for="item in options['assignment.ImagesAssignment']?.[0].isDelayText"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <multi-input
        clearable
        v-model="form.task_no"
        style="width: 200px"
        placeholder="任务单号,批量搜索,一行一个"
      ></multi-input>
      <VGroup>
        <el-select class="selectClass !w-[100px]" v-model="form.personnelRange.type">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <select-personnel
          v-model="form.personnelRange.value"
          :multiple="true"
          placeholder="请选择"
        ></select-personnel>
      </VGroup>
      <SelectTaskType
        v-model="form.task_type"
        placeholder="任务类型"
        multiple
        clearable
      ></SelectTaskType>
      <el-select
        v-model="form.product_type"
        class="!w-[160px]"
        placeholder="商品类型"
        clearable
      >
        <el-option
          v-for="item in options['assignment.ImagesAssignment']?.[0].productTypeText"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-date-picker
        v-model="form.performance_month"
        type="month"
        value-format="YYYY-MM-DD"
        placeholder="请选择绩效月份"
      />
      <el-select v-model="form.pid" class="!w-[160px]" placeholder="是否子任务" clearable>
        <el-option
          v-for="item in subTaskOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-select
        v-model="form.is_attach"
        class="w-50"
        placeholder="是否上传任务要求附件"
        clearable
      >
        <el-option
          v-for="item in attachOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>

      <teleport v-if="tabsLoad" to="#design-task">
        <el-tabs class="w-full" v-model="form.status" @tab-click="handleClick">
          <el-tab-pane
            :label="item.label"
            :name="item.name"
            v-for="(item, index) in tabList"
            :key="index"
          >
            <template #label>
              {{ item.label }}(<span
                :class="form.status == item.name ? 'base-text-color' : 'text-[#999999]'"
                >{{ item.count }}</span
              >)
            </template>
          </el-tab-pane>
        </el-tabs>
      </teleport>
    </template>
    <template #toolbar_btns>
      <div id="design-task" class="w-full" v-dom-load="() => (tabsLoad = true)"></div>
      <VButton
        auth="/goods/task/picture/add"
        type="primary"
        @click="pictureTaskFun('add')"
        >+ 新增任务</VButton
      >
      <VButton
        auth="/goods/task/picture/batchPerson"
        v-show="[1, 2].includes(activeName) || !activeName"
        @click="handleBatch('batchDistriBution')"
        >批量分配人员</VButton
      >
      <VButton
        auth="/goods/task/picture/sumitAudit"
        v-show="[2, 5, 6, 8].includes(activeName) || !activeName"
        @click="handleBatch('haveReviewed')"
        >提交审核</VButton
      >
      <VButton
        auth="/goods/task/picture/batchAudit"
        v-show="[3].includes(activeName) || !activeName"
        @click="handleBatch('designReview')"
        >设计审核</VButton
      >
      <VButton
        auth="/goods/task/picture/operation-audit"
        v-show="[4].includes(activeName) || !activeName"
        @click="handleBatch('operationAudit')"
        >运营审核</VButton
      >
      <VButton auth="/goods/task/picture/copy" @click="handleCopy()">复制</VButton>
      <el-dropdown @command="batchOptionsEvent">
        <el-button>
          批量操作<i
            style="font-size: 10px !important"
            class="dk-iconfont icon-ArrowDown"
          />
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="(item, index) in batchFilterOptions"
              :key="index"
              :command="item.value"
              >{{ item.label }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div class="ml-auto flex items-center cursor-pointer gap-3">
        <el-dropdown @command="taskOptionsEvent">
          <el-button>
            数据看板<i
              style="font-size: 10px !important"
              class="dk-iconfont icon-ArrowDown"
            />
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(item, index) in statisticsoardOptions"
                :key="index"
                :command="item"
                >{{ item.label }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown @command="taskOptionsEvent">
          <el-button>
            进度看板<i
              style="font-size: 10px !important"
              class="dk-iconfont icon-ArrowDown"
            />
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(item, index) in taskBoardOptions"
                :key="index"
                :command="item"
                >{{ item.label }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="handleCustom">自定义字段</el-button>
        <VButton auth="/goods/task/picture/export" @click="handleExport">
          <i class="dk-iconfont icon-Upload" />导出
        </VButton>
      </div>
    </template>
  </VTable>
  <checkImage ref="refCheckImage" :imgList="imgList" />
  <pictureDialogConption ref="diaLog" @query="queryForm"></pictureDialogConption>
  <pictureListConption ref="refPictureList" />
  <addTaskConption ref="refAddTask" @query="queryForm" />
  <VLog ref="logRef" :api="queryLogList" :isSearch="true" />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <customFields
    ref="customFieldsRef"
    apiName="picture"
    :columns="columns"
    @filter-table="getCustomFieldsList"
  >
  </customFields>
  <copyDialog v-model="copyVisible" :data="copyData" @close="copyData = []" />
  <LabelModal ref="labelModalRef"></LabelModal>
  <operateReviewRecord ref="operateReviewRecordRef"></operateReviewRecord>
  <editPerformance ref="editPerformanceRef"></editPerformance>
  <pictureStatistics ref="pictureStatisticsRef"></pictureStatistics>
  <downloadImage ref="downloadImageRef"></downloadImage>
</template>

<script setup lang="jsx" name="DesignTask">
import {
  queryLogList,
  imgGetList,
  cancelTask,
  getTaskStatistics,
  getCustomFields,
  imagesAssignmentClaimTask,
} from "./api";
import { ImgDownloadTask } from "@/api/index";
import addTaskConption from "./components/addTask.vue";
import checkImage from "./components/checkImage.vue";
import pictureDialogConption from "./components/pictureDialog.vue";
import pictureListConption from "./components/pictureList.vue";
import VLog from "@/components/VLog/index.vue";
import { ElMessage, ElMessageBox, ElSelect } from "element-plus";
import { nextTick, onMounted, ref, toRefs } from "vue";
import useUserStore from "@/store/modules/user";
import DerivedCenter from "@/components/DerivedCenter";
import customFields from "./components/customFields";
import SelectCategory from "@/components/SelectCategory";
import copyDialog from "./components/copyDialog";
import { useRoute, useRouter } from "vue-router";
import LabelModal from "../../statement/design-performance/components/LabelModal";
import operateReviewRecord from "./components/operate-review-record.vue";
import editPerformance from "./components/editPerformance.vue";
import {
  subTaskOptions,
  batchOptions,
  userOptions,
  dateOptions,
  taskBoardOptions,
  productOptions,
  statisticsoardOptions,
  attachOptions,
} from "./data.js";
import pictureStatistics from "./components/pictureStatistics.vue";
import { setStorage, getStorage } from "@/utils/storage";
import { findUrlInList } from "@/utils/index.js";
import SelectTaskType from "@/components/Selects/SelectTaskType/index.vue";
import ProductList from "./components/ProductList/index.vue";
import downloadImage from "./components/downloadImage";
let options = reactive(inject("options"));

let route = useRoute();
const router = useRouter();
const store = useUserStore();

const tabsLoad = ref(false);

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: false,
  multiple: true,
};

let activeName = ref("");
const tableRef = ref();
const logRef = ref();
const diaLog = ref(null);
const refPictureList = ref(null);
const refAddTask = ref(null);
const refCheckImage = ref(null);
const imgList = ref([]);

const data = reactive({
  typeList: [],
  tabList: [
    {
      label: "全部",
      name: "",
      count: 0,
    },
    {
      label: "待分配人员",
      name: 1,
      count: 0,
    },
    {
      label: "待处理",
      name: 2,
      count: 0,
    },
    {
      label: "处理中",
      name: 8,
      count: 0,
    },
    {
      label: "待设计审核",
      name: 3,
      count: 0,
    },
    {
      label: "待运营审核",
      name: 4,
      count: 0,
    },
    {
      label: "审核未通过",
      name: 5,
      count: 0,
    },
    {
      label: "已完成",
      name: 6,
      count: 0,
    },
    {
      label: "已取消",
      name: 7,
      count: 0,
    },
  ],
  expandActives: [],
  searchOptions: [],
  batchFilterOptions: [],
  options: {},
  CustomFieldsList: [],
  isRefreshTable: false,
  columns: [
    { type: "checkbox", field: "checkbox", width: 60 },
    {
      title: "任务单号",
      field: "task_no",
      minWidth: 200,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <div class={["font-size-10px", `taskBgColor${row.status}`]}>
                {row.status_text}
              </div>
              <div class={["font-size-10px", "ml-4", `priorityBgColor${row.priority}`]}>
                {row.priority_text}
              </div>
              <div class="flex">
                <VText
                  type="button"
                  value={row.task_no}
                  copy={true}
                  onClick={() => pictureTaskFun("view", row.id)}
                ></VText>
                {row.pid ? (
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content={row.belongs_task?.task_no}
                    placement="top"
                  >
                    <div class="bg-[#E50113] text-[#fff] w-5 h-5 rounded-full text-center">
                      子
                    </div>
                  </el-tooltip>
                ) : (
                  ""
                )}
              </div>
            </div>,
          ];
        },
      },
    },
    {
      title: "预期完成时间",
      field: "expected_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <div>
                <span
                  style="color:#fff;border-radius: 5px 0px 5px 5px;padding:1px 4px;"
                  class={["text-xs", row.is_delay == 1 ? "bgColorA" : "bgColorC"]}
                >
                  {row.is_delay ? "已延期" : "未延期"}
                </span>
              </div>
              <div>{row.expected_time}</div>
            </div>,
          ];
        },
      },
    },
    {
      title: "任务等级/类型",
      field: "task_priority",
      minWidth: 140,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["task_type", "task_priority"])}
              />{" "}
              任务等级/类型
            </div>
          );
        },
        default: ({ row }) => {
          const task_type_text =
            (row.task_type_text.length && row.task_type_text.join("、")) || "--";
          return [
            <div>
              <div>
                {row.task_priority_text && (
                  <span
                    class={`bgColor${row.task_priority_text}`}
                    style={"text-align:center;height: 20px;padding: 0 6px"}
                  >
                    {row.task_priority_text}
                  </span>
                )}
              </div>
              <div class="overflow-line2">
                {task_type_text && (
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content={task_type_text}
                    placement="top"
                  >
                    <span class="flex-1">{task_type_text}</span>
                  </el-tooltip>
                )}
              </div>
            </div>,
          ];
        },
      },
    },
    {
      title: "图片数量",
      field: "image_total",
      minWidth: 190,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["image_total"])}
              />
              图片数量
            </div>
          );
        },
        default: ({ row, rowIndex }) => {
          return [
            <div class={"clearfix"}>
              <div>
                任务要求：
                <span
                  style={
                    "text-overflow:ellipsis ;text-overflow:ellipsis ; white-space:nowrap ; overflow:hidden;white-space:nowrap ;overflow:hidden;max-width:80px;"
                  }
                >
                  {row.image_total_text}{" "}
                </span>
              </div>
              <div class="flex items-center">
                <div class="mr-2">
                  <span class="">已上传：</span>{" "}
                  {row.uploaded_image_count > 0 ? (
                    <span
                      class="text-[#3366f1] cursor-pointer"
                      onclick={() => checkImageFun(row)}
                    >
                      {row.uploaded_image_count}张
                    </span>
                  ) : (
                    "0张"
                  )}
                </div>
                <VButton
                  auth="/goods/task/picture/download"
                  type="primary"
                  link
                  onClick={() => handleDownload(row)}
                >
                  图片下载
                </VButton>
              </div>
            </div>,
          ];
        },
      },
    },
    {
      title: "SKU信息",
      field: "sku",
      width: 280,
      slots: {
        default: ({ row }) => {
          return <ProductList list={row.images_assignment_sku}></ProductList>;
        },
      },
    },
    {
      title: "品牌",
      field: "brand",
      minWidth: 120,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["brand_id"])}
              />
              品牌
            </div>
          );
        },
        default: ({ row, rowIndex }) => {
          const brand_id_text = [];
          row.brand_id_text &&
            row.brand_id_text.forEach((i) => {
              brand_id_text.push(i.name);
            });
          return [
            <div class="">
              <el-tooltip
                class="item"
                effect="dark"
                content={brand_id_text.join("、")}
                placement="top"
              >
                <div className="overflow-line2 line-clamp-2" style="width: 100px">
                  {brand_id_text.join("、")}
                </div>
              </el-tooltip>
            </div>,
          ];
        },
      },
    },
    {
      title: "任务备注",
      field: "task_remark",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.task_remark || ""}
                placement="top"
              >
                <div class="overflow-line2" style="width: 200px">
                  {row.task_remark}
                </div>
              </el-tooltip>
            </div>,
          ];
        },
      },
    },
    {
      title: "审核备注",
      field: "remark",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <div class="">设计审核备注：</div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.designer_comment || ""}
                placement="top"
              >
                <div class="overflow-line2" style="width: 200px">
                  {row.designer_comment}
                </div>
              </el-tooltip>
              <div class="">运营审核备注：</div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.operators_comment || ""}
                placement="top"
              >
                <div class="overflow-line2" style="width: 200px">
                  {row.operators_comment}
                </div>
              </el-tooltip>
            </div>,
          ];
        },
      },
    },
    {
      title: "处理人备注",
      field: "handle_remark",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.handle_remark || ""}
                placement="top"
              >
                <div class="overflow-line2" style="width: 200px">
                  {row.handle_remark}
                </div>
              </el-tooltip>
            </div>,
          ];
        },
      },
    },
    {
      title: "产品开发人员",
      field: "developer_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["developer_user"])}
              />
              产品开发人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.developer_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "运营人员",
      field: "operators_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["operators_user_ids"])}
              />
              运营人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.operators_user_ids_text.join("、") || "--"}</div>;
        },
      },
    },
    {
      title: "图片处理人员",
      field: "designer_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["designer_user"])}
              />
              图片处理人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.designer_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "摄影人员",
      field: "photography_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["photography_user"])}
              />
              摄影人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.photography_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "编辑人员",
      field: "edit_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["edit_user"])}
              />
              编辑人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.edit_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "渲染人员",
      field: "render_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["render_user"])}
              />
              渲染人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.render_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "协助人员",
      field: "assistance_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["assistance_user"])}
              />
              协助人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.assistance_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "设计审核人",
      field: "user3",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["designer_reviewer"])}
              />
              设计审核人
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.designer_reviewer_text || "--"}</div>;
        },
      },
    },
    {
      title: "运营审核人",
      field: "review_user",
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.operations_reviewer_text || "--"}</div>;
        },
      },
    },
    {
      title: "运营审核情况",
      field: "operate-review-record",
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return (
            <div
              class="base-text-color cursor-pointer"
              onClick={() => handleOperateRecord(row.id)}
            >
              点击查看
            </div>
          );
        },
      },
    },
    {
      title: "绩效标签查看",
      field: "performance_label",
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return (
            <div
              class="base-text-color cursor-pointer"
              onClick={() => handlePerformanceLabel(row.id)}
            >
              点击查看
            </div>
          );
        },
      },
    },
    {
      title: "创建人",
      field: "create_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["create_user"])}
              />
              创建人
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.create_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "创建时间",
      field: "create_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.create_time || "--"}</div>;
        },
      },
    },
    {
      title: "部门分配开始时间",
      field: "assignment_time_start",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.assignment_time_start || "--"}</div>;
        },
      },
    },
    {
      title: "部门分配结束时间",
      field: "assignment_time_end",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.assignment_time_end || "--"}</div>;
        },
      },
    },
    {
      title: "提交审核时间",
      field: "review_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.process_time || "--"}</div>;
        },
      },
    },
    {
      title: "设计审核时间",
      field: "designer_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.designer_time || "--"}</div>;
        },
      },
    },
    {
      title: "运营审核时间",
      field: "operators_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.operators_time || "--"}</div>;
        },
      },
    },
    {
      title: "更新时间",
      field: "update_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.update_time || "--"}</div>;
        },
      },
    },
    {
      title: "绩效月份",
      field: "performance_month",
      sortable: true,
      minWidth: 160,
      headerRowClassName: "flex",
      slots: {
        header: ({ row }) => {
          return (
            <span class="flex items-center fl">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["performance_month"])}
              />
              绩效月份
            </span>
          );
        },
        default: ({ row }) => {
          return <div>{row.performance_month || "--"}</div>;
        },
      },
    },
    {
      title: "是否超额任务",
      field: "is_excess_task",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <span class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["is_exceed_task"])}
              />
              是否超额任务
            </span>
          );
        },
        default: ({ row }) => {
          return <div>{row.is_exceed_task_text || "--"}</div>;
        },
      },
    },
    {
      title: "任务领取人",
      field: "claim_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <span class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["claim_user"])}
              />
              任务领取人
            </span>
          );
        },
        default: ({ row }) => {
          return <div>{row.claim_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "任务领取时间",
      field: "claim_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.claim_time || "--"}</div>;
        },
      },
    },
    {
      title: "操作",
      field: "operation",
      width: 170,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }) => {
          // 1 待分配 2 待处理 3待设计审核 4待运营审核 5 审核未通过 6已完成 7已取消
          const showRule = {
            edit: [1, 2, 3, 4, 5, 8], // 编辑
            cancel: [1, 2, 3, 4, 5, 8], // 取消
          };
          return [
            <div>
              <div>
                {showRule["edit"].includes(row.status) && (
                  <VButton
                    auth="/goods/task/picture/edit"
                    link
                    type="primary"
                    onClick={() => pictureTaskFun("edit", row.id)}
                  >
                    编辑
                  </VButton>
                )}
                {showRule["cancel"].includes(row.status) && (
                  <VButton
                    auth="/goods/task/picture/cancel"
                    link
                    type="danger"
                    onclick={() => handleCancelTask(row.id)}
                  >
                    取消
                  </VButton>
                )}
                <el-button link type="primary" onClick={() => logRef?.value.open(row.id)}>
                  日志
                </el-button>
              </div>
              <div>
                <VButton
                  auth="/goods/task/picture/edit-performance"
                  type="primary"
                  link
                  onClick={() => handlePerformance(row.id)}
                >
                  绩效编辑
                </VButton>
                {row.pid === 0 ? (
                  <VButton
                    auth="/goods/task/picture/sub-task"
                    type="primary"
                    link
                    onClick={() => pictureTaskFun("subTask", row.id)}
                  >
                    子任务创建
                  </VButton>
                ) : (
                  ""
                )}
              </div>
            </div>,
          ];
        },
      },
    },
  ],
});
const {
  tabList,
  expandActives,
  batchFilterOptions,
  CustomFieldsList,
  isRefreshTable,
  columns,
} = toRefs(data);
// 列表配置
const tableOptins = reactive({
  // rowConfig: { height: 60 },
  showOverflow: false,
  showHeaderOverflow: false,
  scrollY: { enabled: false },
  formConfig: {
    save: "picture",
    remove: "picture",
    data: {
      productName: { type: "sku", value: "" },
      dateRange: { type: "create_time", value: [], range: true },
      personnelRange: { type: "create_user", value: [], range: false },
      status: "",
    },
  },
  columns: [],
  sortConfig: { remote: true, trigger: "cell", orders: ["desc", "asc", null] }, // 默认远程排序
  proxyConfig: {
    seq: true,
    filter: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form, sorts }) =>
        new Promise((resolve) => {
          if (sorts.length && sorts[0].order != "null") {
            form.order_key = sorts[0].field;
            form.order_method = sorts[0].order;
          } else {
            form.order_key = "";
            form.order_method = "";
          }
          getCount(form);

          imgGetList({ ...page, ...form }).then((res) => {
            resolve({
              data: res.data,
              total: res.total,
            });
          });
        }),
    },
  },
});

const getCount = async (form) => {
  try {
    const res = await getTaskStatistics({
      ...form,
      status: "",
    });
    tabList.value = tabList.value.map((i) => {
      res.data.filter((j) => {
        if (i.name === j.status) {
          i.count = j.count;
        }
      });
      return i;
    });
  } catch (e) {
    throw Error(e);
  }
};

// 查看图片
// 多属性图 2
// 详情图 3
// 橱窗图 1
const checkImageFun = (row) => {
  if (!row.uploaded_image_count) {
    return;
  }
  refCheckImage?.value.open(row.id);
};

watch(
  () => route.query,
  (newVal, oldVal) => {
    if (store.picture_spu?.spu) {
      nextTick(() => {
        refAddTask?.value.open("add", store.picture_spu);
        store.createPictureSpu({});
      });
    }
  }
);

// 获取自定义字段
const getCustomFieldsList = async (val) => {
  try {
    const res = await getCustomFields({
      apiName: "picture",
    });
    CustomFieldsList.value = res.data;
    await filterFields();
  } catch (e) {
    throw Error(e);
  }
};

const filterFields = async (val) => {
  if (CustomFieldsList.value?.length) {
    tableOptins.columns = mergedColumns();
    isRefreshTable.value = false;
    tabsLoad.value = false;
    nextTick(() => {
      isRefreshTable.value = true;
    });
  } else {
    tableOptins.columns = columns.value;
    isRefreshTable.value = false;
    nextTick(() => {
      isRefreshTable.value = true;
    });
  }
};

const mergedColumns = () => {
  // 提取 checkbox 和 operation 列
  const checkboxColumn = columns.value.find((column) => column.field === "checkbox");
  const operationColumn = columns.value.find((column) => column.field === "operation");

  // 生成中间列
  const middleColumns = CustomFieldsList.value
    .filter(
      (column) =>
        column.show === 1 && column.field !== "checkbox" && column.field !== "operation"
    )
    .map((customColumnConfig) => {
      const finalColumns = columns.value.find(
        (column) => column.field === customColumnConfig.field
      );
      return finalColumns
        ? { ...finalColumns, ...{ show: customColumnConfig.show } }
        : null;
    })
    .filter((column) => column !== null);

  // 合并列
  const finalColumns = [
    ...(checkboxColumn
      ? [columns.value.find((column) => column.field === "checkbox")]
      : []),
    ...middleColumns,
    ...(operationColumn
      ? [columns.value.find((column) => column.field === "operation")]
      : []),
  ];

  return finalColumns;
};

onMounted(async () => {
  // fetchOption();
  getCustomFieldsList();
  if (store.picture_spu?.spu) {
    nextTick(() => {
      refAddTask?.value.open("add", store.picture_spu);
      store.createPictureSpu({});
    });
  }

  batchFilterOptions.value = batchOptions.filter((i) => {
    if ((window.BTN_AUTH || []).includes(i.auth) || !i.auth) {
      return i;
    }
  });
});

const handleCancelTask = (id) => {
  ElMessageBox.confirm(
    "是否确认取消任务？点击确认后执行取消，并飞书通知任务创建/处理/审核人员。(只允许取消状态为“待分配人员”、“待处理”、“审核未通过”的任务)",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    cancelTask({
      id: [id],
    }).then(() => {
      ElMessage({
        message: "取消任务处理成功",
        type: "success",
      });
    });
    queryForm();
  });
};

const handleBatch = async (type, limit) => {
  const recordsData = getSelectRow();
  let falge = null;
  let records = recordsData?.map((row) => row.id);
  if (!records?.length) {
    return ElMessage({
      message: "请先勾选",
      type: "error",
    });
  }
  if (!limit && records.length > limit) {
    return ElMessage({
      message: `只能选择${limit}个上传`,
      type: "error",
    });
  }
  if (type == "designReview") {
    records = [];
    let batchData =
      recordsData.some((item) => item.status === 3) &&
      recordsData.some((item) => item.status === 4);
    if (batchData) {
      return ElMessage({
        message: "只能选择待设计审核数据,不能一起选择!",
        type: "warning",
      });
    }
    let ids3 = recordsData?.filter((item) => item.status == 3)?.map((it) => it.id);
    if (ids3?.length) {
      records = ids3;
      falge = 3;
    }
    if (!records?.length) {
      return ElMessage({
        message: "只能选择待设计审核数据!",
        type: "warning",
      });
    }
  } else if (type == "operationAudit") {
    records = [];
    let batchData =
      recordsData.some((item) => item.status === 3) &&
      recordsData.some((item) => item.status === 4);
    if (batchData) {
      return ElMessage({
        message: "只能选择待运营审核数据,不能一起选择!",
        type: "warning",
      });
    }
    let ids4 = recordsData?.filter((item) => item.status == 4)?.map((it) => it.id);
    if (ids4?.length) {
      records = ids4;
      falge = 4;
    }
    if (!records?.length) {
      return ElMessage({
        message: "只能选择待运营审核数据!",
        type: "warning",
      });
    }
  } else if (type == "batchDistriBution") {
    records = [];
    let ids5 = recordsData?.filter((item) => item.status == 1)?.map((it) => it.id);
    if (ids5?.length) {
      records = ids5;
      falge = 5;
    }
    if (!records?.length) {
      return ElMessage({
        message: "只能选择待分配数据!",
        type: "warning",
      });
    }
  } else if (type == "taskClaim") {
    const records = getSelectRow().map((i) => i.id);

    try {
      const res = await imagesAssignmentClaimTask({ task_id: records });
      ElMessage.success("操作成功");
      queryForm();
    } catch (e) {
      throw Error(e);
    }
    return;
  }
  diaLog.value.open(type, records, falge);
};

const handleCopy = () => {
  if (getSelectRow().length > 1) {
    return ElMessage({
      message: "只能复制一条任务",
      type: "error",
    });
  }
  const records = getSelectRow();
  if (records[0]?.pid) {
    ElMessage.error("暂不支持子任务的复制");
    return;
  }

  pictureTaskFun("copy", records[0].id);
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const handleClick = (val) => {
  const form = tableRef.value.getForm();
  tableRef.value.setForm({
    ...form,
    status: val.props.name,
  });
  refresh();
};

// 新增/编辑
const pictureTaskFun = (type, id) => {
  nextTick(() => {
    refAddTask?.value.open(type, id);
  });
};

const clearExpandActives = () => {
  expandActives.value.length = 0;
};

const queryForm = () => {
  clearExpandActives();
  nextTick(() => {
    tableRef.value.query();
  });
};

const DerivedCenterRef = ref();
const handleExport = () => {
  const records = getSelectRow().map((i) => {
    return i.task_no;
  });

  const uniqueArray = [...new Set(records)];

  let condition = {};
  if (uniqueArray.length) {
    condition.task_no = uniqueArray;
  } else {
    condition = tableRef.value.getQueryForm();
  }
  DerivedCenterRef.value.open({
    tag_name: "images-assignment",
    condition,
  });
};

const customFieldsRef = ref();
const handleCustom = () => {
  customFieldsRef.value.open(CustomFieldsList.value);
};

// 图片下载
const downloadImageRef = ref();
const handleDownload = async (row) => {
  if (row.uploaded_image_count == 0) {
    ElMessage.error("暂无可下载图片");
    return;
  }
  downloadImageRef.value.open(row);
  // try {
  //   const res = await ImgDownloadTask({
  //     source: 2,
  //     gallery_id: row.id,
  //   });
  //   ElMessage.success(
  //     "发起图片下载成功，请稍后前往基础管理-图片下载任务中进行图片包下载"
  //   );
  // } catch (e) {
  //   throw Error(e);
  // }
};

const changeCategory = (val) => {
  if (val && val.length) {
    const lastLevelIDs = val.map((categoryPath) => categoryPath[categoryPath.length - 1]);
    const form = tableRef.value.getForm();
    setForm({ ...form, category_id: lastLevelIDs });
  } else {
    const form = tableRef.value.getForm();
    setForm({ ...form, category_id: 0 });
  }
};

const copyData = ref([]);
const copyVisible = ref(false);
const batchOptionsEvent = (val) => {
  const records = getSelectRow();
  if (records.length == 0) {
    return ElMessage({
      message: "至少选择一项",
      type: "error",
    });
  }
  if (val == "extractSku") {
    const skuList = [];
    records?.forEach((i) => {
      i.images_assignment_sku.forEach((j) => {
        skuList.push(j.sku);
      });
    });
    const filteredArray = [...new Set(skuList?.filter((item) => item !== ""))];
    const sku = filteredArray.join("\n");
    copyData.value = sku;
    copyVisible.value = true;
    return;
  }
  handleBatch(val, records[0].task_id);
};

const setForm = (val) => {
  nextTick(() => {
    tableRef.value.setForm(val);
  });
};

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    queryForm();
    event.stopPropagation();
  }
};

// 标签查看
const labelModalRef = ref();
const handlePerformanceLabel = (id) => {
  labelModalRef.value.open("view", { id });
};
// 运营审核情况查看
const operateReviewRecordRef = ref();
const handleOperateRecord = (id) => {
  operateReviewRecordRef.value.open(id);
};
// 绩效编辑
const editPerformanceRef = ref();
const handlePerformance = (id) => {
  editPerformanceRef.value.open(id);
};

const pictureStatisticsRef = ref();
const handleStatistics = (field) => {
  const params = tableRef.value.getQueryForm();
  pictureStatisticsRef.value.open({ type: 1, field, params });
};

const taskOptionsEvent = ({ value, path }) => {
  const is_router_menu = findUrlInList(getStorage("menuData") || [], value);
  if (!is_router_menu) {
    ElMessage.error("暂无页面权限");
    return;
  }
  router.push({
    path,
  });
};

const expandFixedRow = (rowIndex, visible) => {
  const beforeExpandActives = deepClone(expandActives.value);
  let needSplice;
  if (rowIndex || rowIndex === 0) {
    const _findIndex = beforeExpandActives.findIndex((v) => v === rowIndex);
    if (visible && _findIndex > -1) {
      needSplice = _findIndex;
    } else {
      beforeExpandActives.push(rowIndex);
    }
  }
  nextTick(() => {
    TKTableUtils.expandFixedRow(beforeExpandActives);
    if (typeof needSplice === "number" && needSplice > -1) {
      beforeExpandActives.splice(needSplice, 1);
    }
    expandActives.value = beforeExpandActives;
  });
};
</script>
<style lang="scss">
@import "./index.scss";
</style>
<style lang="scss" scoped>
.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}
</style>
